package situ.com.mall;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    public static final int UPDATE = 0x1;
    private ListView listView;
    private List<Product> list;

    //消息处理者,创建一个Handler的子类对象,目的是重写Handler的处理消息的方法(handleMessage())
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE:
                    listView.setAdapter(new MyBaseAdapter(list));
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        /*sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });*/
        sendRequest.setOnClickListener(this);
        listView = (ListView) findViewById(R.id.listView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_request:
                sendRequestWithOkHttp();
                break;
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            // 指定访问的服务器地址是电脑本机
                            .url("http://192.168.110.213:8085/product/list")
                            .build();
                    Response response = client.newCall(request).execute();
                    // json: JSONResult
                    String responseData = response.body().string();
                    parseJSONWithGSON(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // Gson：实现json字符串和java对象之间的转换
    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        JSONResult<Product> jsonResult = gson.fromJson(jsonData,  new TypeToken<JSONResult<Product>>(){}.getType());
        System.out.println(jsonResult);
        list = (List<Product>) jsonResult.getData();
        /*for (Product product : list) {
            System.out.println(product);
        }*/

        Message msg = new Message();
        msg.what = UPDATE;
        handler.sendMessage(msg);
    }

    class MyBaseAdapter extends BaseAdapter {
        private List<Product> list;

        public MyBaseAdapter(List<Product> list) {
            this.list = list;
        }

        // 得到item的总数量
        @Override
        public int getCount() {
            return list.size();
        }

        // 返回指定position位置的条目对象
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        // 返回item的id
        @Override
        public long getItemId(int position) {
            return position;
        }

        // 将数据和布局绑定，每绑定一行就调用一次getView
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("position: " + position);
            ViewHolder viewHolder;
            // 这个if-else结构是为了缓存，避免每次都去加载
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView)convertView.findViewById(R.id.imageView);
                viewHolder.textView = (TextView)convertView.findViewById(R.id.textView);
                // 换到到convertView
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // 设置每个Item左边的图片
            Product product = list.get(position);
            System.out.println(product.getMainImageUrl());
            Glide.with(MainActivity.this).load(product.getMainImageUrl()).into(viewHolder.imageView);
            viewHolder.textView.setText(product.getName());

            return convertView;
        }

        // 描述每一个Item布局
        class ViewHolder{
            ImageView imageView;
            TextView textView;
        }
    }


}
